import * as path from 'path';
import { workspace, ExtensionContext, commands, Uri,CompletionList } from 'vscode';
import { listener } from './color'

import {
	LanguageClient,
	LanguageClientOptions,
	ServerOptions,
	TransportKind
} from 'vscode-languageclient/node';
// import { getShellContent, insideShell } from './shellSupport';

let client: LanguageClient;

export function activate(ec: ExtensionContext) {
	// 颜色
	workspace.onDidChangeTextDocument(listener);

	const serverModule = ec.asAbsolutePath(
		path.join('server', 'out', 'server')
	);
	const debugOptions = { execArgv: ['--nolazy', '--inspect=6009'] };

	const serverOptions: ServerOptions = {
		run: { module: serverModule, transport: TransportKind.ipc },
		debug: {
			module: serverModule,
			transport: TransportKind.ipc,
			options: debugOptions
		}
	};

	// const virtualDocumentContents = new Map<string, string>();
	// workspace.registerTextDocumentContentProvider('embedded-content', {
	// 	provideTextDocumentContent: uri => {
	// 		const originalUri = uri.path.slice(1).slice(0, -4);
	// 		const decodedUri = decodeURIComponent(originalUri);
	// 		return virtualDocumentContents.get(decodedUri);
	// 	}
	// });

	const clientOptions: LanguageClientOptions = {
		documentSelector: [{ scheme: 'file', language: 'tintin' }],
		synchronize: {
			fileEvents: workspace.createFileSystemWatcher('**/.clientrc')
		},
		// middleware: {
		// 	provideCompletionItem: async (document, position, context, token, next) => {
		// 		if (!insideShell(document,position)){
		// 			return await next(document,position,context,token);
		// 		}

		// 		const originalUri = document.uri.toString();
		// 		virtualDocumentContents.set(originalUri, getShellContent(document,position));
		// 		console.log("virtualDocumentContents",virtualDocumentContents.get(originalUri));
		// 		const vdocUriString = `embedded-content://shell/${encodeURIComponent(
		// 			originalUri
		// 		)}.tin`;
		// 		const vdocUri = Uri.parse(vdocUriString);
		// 		return await commands.executeCommand<CompletionList>(
		// 			'vscode.executeCompletionItemProvider',
		// 			vdocUri,
		// 			position,
		// 			context.triggerCharacter
		// 		);
		// 	}
		// }
	};

	client = new LanguageClient(
		'tintinServer',
		'Tintin++ Language Server',
		serverOptions,
		clientOptions
	);

	client.start();
}

export function deactivate(): Thenable<void> | undefined {
	if (!client) {
		return undefined;
	}
	return client.stop();
}